<!-- 远程控制中心 -->
<template>
  <div class="app-container no-padding remote-container">
    <div id="map"/>
    <div class="bgLeft"/>
    <div class="bgRight"/>
    <div class="bgTop"/>
    <div class="bgBottom"/>
    <!-- 中间报警弹窗 -->
    <div v-if="showModel" :style="{backgroundImage: 'url('+ dialog +')'}" class="dialog-img">
      <p class="dialog-title">实时报警</p>
      <ul>
        <li><span class="left">{{ dialogData.park_name }}</span><span class="right">{{ dialogData.building_name }}</span></li>
        <li><span class="left">{{ dialogData.loop }}</span><span class="right">{{ dialogData.position?dialogData.position:'' }}</span></li>
      </ul>
      <div class="date">{{ dialogData.date }}</div>
      <span class="close el-icon-close" @click="closeDialog"/>
    </div>
    <!-- 左侧内容 -->
    <div class="left-content">
      <!-- 左侧 logo -->
      <div class="top-left"><img :src="logo" class="logo-img"><span>上海励尔信息科技有限公司</span></div>
      <!-- 左侧 单位信息 -->
      <div class="company-info">
        <p class="title">单位信息</p>
        <ul>
          <li>单位名称：{{ corpInfo.name }}</li>
          <li>地址：{{ corpInfo.address }}</li>
        </ul>
        <ul>
          <li>联系人：{{ corpInfo.link_user }}</li>
          <li>联系电话：{{ corpInfo.link_user_mobile }}</li>
        </ul>
        <ul class="quarter">
          <li>单位数：{{ corpInfo.corp_number }}</li>
          <li>建筑群数：{{ corpInfo.park_number }}</li>
          <li>建筑数：{{ corpInfo.building_number }}</li>
          <li>分区数：{{ corpInfo.fire_zone }}</li>
        </ul>
      </div>
      <!-- 左侧 综合评分 -->
      <div class="comprehensiveScore score">
        <p class="title">综合评分</p>
        <ul>
          <li>
            <span><i>{{ comprehensiveScoreNum }}</i>分</span>
            <el-progress :percentage="comprehensiveScoreNum" :show-text="false" color="#F49156" type="circle"/>
            <p class="level-info">安全等级：{{ levelName }}</p>
          </li>
          <li class="last">
            <div>
              <p :style="{'color':'#7BFED4'}">优</p>
              <span>{{ distinction }}</span>
              <el-progress :show-text="false" :percentage="80" color="#7BFED4"/>
            </div>
            <div>
              <p :style="{'color':'#F0B56F'}">良</p>
              <span>{{ good }}</span>
              <el-progress :show-text="false" :percentage="50" color="#F0B56F"/>
            </div>
            <div>
              <p :style="{'color':'#FC5252'}">差</p>
              <span>{{ poor }}</span>
              <el-progress :show-text="false" :percentage="10" color="#FC5252"/>
            </div>
          </li>
        </ul>
      </div>
      <!-- 左侧  隐患排名 -->
      <div class="hiddenDanger">
        <p class="title">分数排名</p>
        <ul>
          <li v-for="(item, index) in hiddenDangerData" :key="index"><span :title="item.companyName">{{ item.companyName }}:</span><span :title="item.hiddenDangerNum" :style="{color: item.color}" class="num">{{ item.hiddenDangerNum }}</span></li>
        </ul>
      </div>
    </div>
    <div class="event-center position-center position-center2">
      <p class="title">事件中心</p>
      <div class="list-info">
        <ul class="list-title"><li>设备名称</li><li>位置</li><li>时间</li><li>处理状态</li></ul>
        <div class="data_list">
          <ul v-for="item in eventCenterList" :key="item.key" :class="item.class"><li :title="item.equipmentName">{{ item.equipmentName }} <img :src="item.icon"></li><li :title="item.loop">{{ item.loop }}</li><li :title="item.date">{{ item.date }}</li><li :title="item.status">{{ item.status }}</li></ul>
        </div>
      </div>
    </div>
    <!-- 设备联网率 -->
    <div class="dangerEquipment">
      <div id="dangerEquipment"/>
    </div>
    <div class="top-right">
      <div id="weather">
        <iframe id="weatherIframe" scrolling="no" src="https://tianqiapi.com/api.php?style=tz&skin=pitaya&appid=94798341&appsecret=1jNVOgNb&vue=1&color=b6b8bf&align=right&paddingtop=2" frameborder="0" height="20" allowtransparency="true"/>
      </div><div id="currentTime" class="dateStr"/>
      <div id="currentDate" class="dateStr"/>
    </div>
    <div class="todayAbnormal">
      <p class="title" style="padding-left:20px;">今日异常</p>
      <ul>
        <li v-for="item in todayAbnormalList" :key="item.corp_id">
          <i :class="item.class"/>
          <p :title="item.corp_name">{{ item.corp_name }}</p>
          <p><span>火警点位数</span><span>{{ item.alarm_point_ids }}</span></p>
          <p><span>火警记录数</span><span>{{ item.alarm_num }}</span></p>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import logo from '@/assets/logo_white.png'
import dialog from '@/assets/remoteControlCenter/dialog.png'
import listDanger from '@/assets/remoteControlCenter/list-danger.png'
import listPosition from '@/assets/remoteControlCenter/list-position.png'
import listShield from '@/assets/remoteControlCenter/list-shield.png'
import listWarning from '@/assets/remoteControlCenter/list-warning.png'
import markerImg from '@/assets/remoteControlCenter/marker.png'
import markerImg2 from '@/assets/remoteControlCenter/marker2.png'
import markerImg3 from '@/assets/remoteControlCenter/marker3.png'
import titleIcon1 from '@/assets/remoteControlCenter/title-icon1.png'
import titleIcon2 from '@/assets/remoteControlCenter/title-icon2.png'
import user from '@/assets/remoteControlCenter/user.png'
import weatherCloudy from '@/assets/remoteControlCenter/weatherCloudy.png'
import weatherFine from '@/assets/remoteControlCenter/weatherFine.png'
import weatherHaze from '@/assets/remoteControlCenter/weatherHaze.png'
import weatherOvercast from '@/assets/remoteControlCenter/weatherOvercast.png'
import weatherRain from '@/assets/remoteControlCenter/weatherRain.png'
import weatherSnow from '@/assets/remoteControlCenter/weatherSnow.png'
import weatherUnknown from '@/assets/remoteControlCenter/weatherUnknown.png'
import AMap from 'AMap'
import $ from 'jquery'
import { parseTime } from '@/utils/index'
import echarts from 'echarts'
import { corpInfo, colligationScore, sortScore, iot, todayAbnormal, buildingList } from '@/api/controlManage'
export default {
  name: 'Order',
  data() {
    return {
      weatherCloudy,
      weatherFine,
      weatherHaze,
      weatherOvercast,
      weatherRain,
      weatherSnow,
      weatherUnknown,
      logo,
      dialog,
      listDanger,
      listPosition,
      listShield,
      listWarning,
      markerImg,
      markerImg2,
      titleIcon1,
      titleIcon2,
      user,
      showModel: false,
      dialogData: {},
      // 单位信息
      corpInfo: {
        address: '',
        building: '',
        link_user: '',
        link_user_mobile: '',
        name: '',
        iot: '',
        corp_number: '',
        park_number: '',
        building_number: '',
        fire_zone: ''
      },
      mapBuildList: [],
      markers: [],
      // 今日隐患
      todayAbnormalList: [],
      // 隐患排名
      hiddenDangerData: [],
      // 安全等级
      levelName: '',
      // 安全分数
      comprehensiveScoreNum: 0,
      // 事件列表
      eventCenterList: [],
      // 优等级数量
      distinction: 0,
      // 良等级数量
      good: 0,
      // 差等级数量
      poor: 0,
      dangerEquipment: null,
      // 设备联网率容器
      map: null,
      scrollEvent: null
    }
  },
  watch: {
    eventCenterList(val) {
      if (val.length > 5 && !this.scrollEvent) {
        this.scrollEventFn()
      }
    }
  },
  created() {
    this.$nextTick(function() {
      window.onresize = function() {
        var height = $('.left-content').height() + 50
        var mHeight = $(document).height()
        if (mHeight > height) {
          $('#map').height(mHeight)
        } else {
          $('#map').height(height)
        }
      }
      var height = $('.left-content').height() + 50
      var mHeight = $(document).height()
      if (mHeight > height) {
        $('#map').height(mHeight)
      } else {
        $('#map').height(height)
      }
      // 隐藏顶部内容、左侧菜单
      $('.navbar').fadeOut()
      $('.sidebar-container').fadeOut()
      $('.main-container').css('margin', 0)
      $('.logo').fadeOut()
      // 实例化右下角设备联网率
      this.dangerEquipment = echarts.init(document.getElementById('dangerEquipment'))
      // 实例化地图
      this.map = new AMap.Map('map', {
        zoom: 17,
        showLabel: true,
        resizeEnable: true,
        rotateEnable: true,
        pitchEnable: true,
        pitch: 55,
        rotation: 0,
        viewMode: '3D', // 开启3D视图,默认为关闭
        buildingAnimation: true, // 楼块出现是否带动画
        expandZoomRange: true,
        zooms: [3, 24],
        forceVector: true,
        mapStyle: 'amap://styles/c2d238d46afa93049b7c3ca434a374d8' //  设置地图的显示样式
      })
      // 初始化内容
      this.init()
      // 右上角时间
      this.writeCurrentDate()
      // 初始化WebSocket发起请求建立连接
      this.initWebSocket()
    })
  },
  destroyed() {
    this.websock.close() // 离开路由之后断开websocket连接
    clearInterval(this.scrollEvent)
    this.scrollEvent = null
  },
  methods: {
    closeDialog() {
      this.showModel = false
    },
    // 轮播事件
    scrollEventFn() {
      const that = this
      var deleteData
      this.scrollEvent = setInterval(function() {
        $('.event-center .data_list').stop().animate({ 'top': '6px' }, function() {
          $('.event-center .data_list').css({ top: '36px' })
          deleteData = that.eventCenterList.shift()
          that.eventCenterList.push(deleteData)
        })
      }, 2000)
    },
    initWebSocket() { // 初始化weosocket
      if (typeof (WebSocket) === 'undefined') {
        this.$message.warning('您的浏览器不支持socket，请更换浏览器后重试')
      } else {
        var token = localStorage.getItem('token')
        const wsuri = process.env.WEBSOCKET_SERVER + '?token=' + token
        this.websock = new WebSocket(wsuri)
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      }
    },
    websocketonopen() { // 连接建立之后执行send方法发送数据
      if (this.websock.readyState) {
        console.log('建立连接')
      }
      console.log('readyState:' + this.websock.readyState)
    },
    websocketonerror(e) { // 连接建立失败重连
      console.log('WebSocket连接发生错误' + e)
      this.initWebSocket()
    },
    websocketonmessage(e) { // 数据接收task_start_at
      console.log('数据接收')
      console.log(e.data)
      const that = this
      const data = JSON.parse(e.data)
      // push_type:
      // 1 火警/故障/屏蔽 事件
      // 2 处理 火警/故障/屏蔽
      // 3 巡更
      // 4 建筑火警/故障数量
      // 有设备名称 事件中心 火警/故障/屏蔽 事件
      if (data.push_type === 1) {
        // 表格处理
        data.class = ''
        data.icon = data.task_type === 1 ? listDanger : data.task_type === 2 ? listWarning : data.task_type === 3 ? listShield : ''
        data.equipmentName = data.mname
        data.status = data.status === 7 ? '未处理' : '已处理'
        data.date = data.task_start_at ? parseTime(data.task_start_at * 1000, '{y}-{m}-{d} {h}:{i}:{s}') : ''
        that.eventCenterList.push(data)
        that.dialogData = data
        that.showModel = true
      // 处理 火警/故障/屏蔽
      } else if (data.push_type === 2) {
        console.log(JSON.stringify(data))
        that.eventCenterList.forEach(item => {
          if (item.task_id === data.task_id) {
            item.status = data.status === 7 ? '未处理' : '已处理'
          }
        })
      // 建筑火警/故障数量
      } else if (data.push_type === 4) {
        // 地图上所有的建筑标注点，修改所对应的报警、故障数量
        console.log(data.buildingList)
        var newArr = []
        that.markers.forEach((it, index) => {
          data.buildingList.forEach(item => {
            if (item.building_id === it.Ce.id) {
              that.markers[index].setMap(null)
              that.markers.splice(index, 1)
              newArr.push(that.getMarker(item))
            }
          })
        })
        that.map.add(newArr)
        that.markers = that.markers.concat(newArr)
      }
    },
    websocketsend(agentData) { // 数据发送
      console.log('数据发送')
      // this.websock.send({'name': '测试'});
    },
    websocketclose(e) { // 关闭
      console.log('断开连接', e)
    },
    init() {
      const that = this
      // 地图默认标注点
      buildingList()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            that.mapBuildList = data.data
            that.map.setCenter([parseFloat(data.data[0].longitude), parseFloat(data.data[0].latitude)])
            that.markers = []
            that.mapBuildList.forEach((item, index) => {
              if (item.longitude && item.latitude) {
                item.longitude = parseFloat(item.longitude)
                item.latitude = parseFloat(item.latitude)
                that.markers.push(that.getMarker(item))
              }
            })
            console.log(that.markers[0].Ce.id)
            that.map.add(that.markers)
          }
        })
        .catch((e) => {
          console.log(e)
        })
      // 今日异常
      todayAbnormal()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            this.todayAbnormalList = []
            data.data.forEach((item, index) => {
              if (index % 4 === 0) {
                item.class = 'circle1'
              } else if (index % 4 === 1) {
                item.class = 'circle2'
              } else if (index % 4 === 2) {
                item.class = 'circle3'
              } else if (index % 4 === 3) {
                item.class = 'circle4'
              }
              this.todayAbnormalList.push(item)
            })
          }
        })
      // 右下角的设备联网率
      iot()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            // console.log(data)
            const XData = []
            data.data.forEach(item => {
              XData.push(item.name)
            })
            var s = $('#dangerEquipment').width() > 400 ? 13 : 10
            this.dangerEquipment.setOption({
              title: {
                text: '设备联网率',
                left: 'left',
                padding: 15,
                textStyle: {
                  fontSize: 18,
                  color: '#fff',
                  fontWeight: 500
                }
              },
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                type: 'scroll',
                orient: 'vertical',
                top: 40,
                right: 0,
                icon: 'circle',
                textStyle: {
                  color: '#fff',
                  fontSize: s
                },
                data: XData
              },
              series: [{
                name: '设备联网率',
                type: 'pie',
                radius: ['50%', '70%'],
                center: ['30%', '60%'],
                data: data.data,
                left: 0,
                right: 0,
                color: ['#fea763', '#28abff', '#6416cf', '#084cf7', '#eb47a0'],
                label: {
                  show: true,
                  formatter: '{d}%'
                },
                labelLine: {
                  length: 5,
                  length2: 5
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }]
            })
          }
        })
        .catch(() => {
        })
      // 单位信息
      corpInfo()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            console.log(data)
            that.corpInfo = data.data
            that.corpInfo.iot = that.corpInfo.iot.length === 0 ? '暂无系统接入' : that.corpInfo.iot.join(',')
          }
        })
        .catch(() => {
        })
      // 评分
      colligationScore()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            this.comprehensiveScoreNum = parseInt(data.data.score)
            this.levelName = data.data.safetyLevel
            this.distinction = data.data.distinction
            this.good = data.data.good
            this.poor = data.data.poor
          }
        })
        .catch((e) => {
          console.log(e)
        })
      // 分数排名
      sortScore()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            console.log(data)
            var color = ''
            this.hiddenDangerData = []
            data.data.forEach(item => {
              if (item.score <= 60) {
                color = '#C02137'
              } else if (item.score > 60 && item.score < 85) {
                color = '#E58451'
              } else {
                color = '#617A5C'
              }
              this.hiddenDangerData.push({
                companyName: item.corp_name,
                hiddenDangerNum: item.score,
                color: color
              })
            })
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 时间
    writeCurrentDate() {
      var now = new Date()
      var year = now.getFullYear() // 得到年份
      var month = now.getMonth() // 得到月份
      var date = now.getDate() // 得到日期
      var hour = now.getHours() // 得到小时
      var minu = now.getMinutes() // 得到分钟
      var sec = now.getSeconds() // 得到秒
      var MS = now.getMilliseconds() // 获取毫秒
      month = month + 1
      if (month < 10) {
        month = '0' + month
      }
      if (date < 10) {
        date = '0' + date
      }
      if (hour < 10) {
        hour = '0' + hour
      }
      if (minu < 10) {
        minu = '0' + minu
      }
      if (sec < 10) {
        sec = '0' + sec
      }
      if (MS < 100) {
        MS = '0' + MS
      }
      var dateStr = year + '/' + month + '/' + date
      var time = hour + ':' + minu + ':' + sec
      // 当前日期赋值给当前日期输入框中（jQuery easyUI）
      $('#currentDate').html(dateStr)
      $('#currentTime').html(time)
      // 设置得到当前日期的函数的执行间隔时间，每1000毫秒刷新一次。
      setTimeout(this.writeCurrentDate, 1000)
    },
    // 生成点位
    getMarker(data) {
      const that = this
      var zoomStyleMapping = {
        5: 11,
        6: 11,
        7: 11,
        8: 11,
        9: 11,
        10: 10,
        11: 9,
        12: 8,
        13: 7,
        14: 6,
        15: 5,
        16: 4,
        17: 3,
        18: 2,
        19: 1,
        20: 0
      }
      // 火警数量是0 故障大于0显示黄色剩下都是蓝色
      var img = data.fireNumber > 0 ? markerImg2 : data.faultNumber > 0 ? markerImg : markerImg3
      var color = data.fireNumber > 0 ? 'style1' : data.faultNumber > 0 ? 'style2' : 'style3'
      var content = '<div class="markerImgStyle2 ' + color + '"><div class="text"><span>' + data.park_name + data.name + '</span><img src="' + titleIcon1 + '" class="icon"><span class="h">' + data.fireNumber + '</span><img src="' + titleIcon2 + '" class="icon"><span class="p">' + data.faultNumber + '</span></div></div>'
      var m = new AMap.ElasticMarker({
        // map: that.map,
        position: new AMap.LngLat(data.longitude, data.latitude),
        zooms: [4, 20],
        cursor: 'pointer',
        id: data.building_id,
        styles: [{
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 20,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 19,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 18,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 17,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 16,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 15,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 14,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 13,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 12,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 11,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 10,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }, {
          icon: {
            img: img,
            size: [86, 102],
            ancher: [43, 82],
            imageSize: [86, 102],
            fitZoom: 9,
            maxScale: 100,
            minScale: 0.125
          },
          label: {
            content: content,
            position: 'TM'
          }
        }],
        zoomStyleMapping: zoomStyleMapping
      })
      m.on('click', item => {
        that.map.setCenter([item.lnglat.lng, item.lnglat.lat])
        that.map.setZoom(10)
      })
      return m
    }
  }
}
</script>
